/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.shelf.web.ShelfAction
   Module Description   :

   Date Created      : 2009/11/30
   Original Author   : ellen.li
   Team              : yaodian100
   TODO:1.上下架的状态。2。必填欄位
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.shelf.web;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.admin.entity.Role;
import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.admin.service.UserService;
import com.yaodian100.core.admin.utils.AdminHelper;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.quotation.service.QuotationService;
import com.yaodian100.ec.quotation.service.QuotationServiceOnline;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;
import com.yaodian100.erp.quotation.remote.Quotation;

/**
 * @author ellen.li
 * 
 */
public class ShelfAction extends ActionSupport implements Preparable {

	/**
	 * serial version
	 */
	private static final long serialVersionUID = -5872758578609930899L;
	private final Logger logger = LoggerFactory.getLogger(ShelfAction.class);
	@Resource
	private ProductService productService;
	@Resource
	private UserService userService;
	@Resource
	private DomainService<Menu> menuService;
	@Resource
	private ShelfService shelfService;
	CommonCriteria crit;
	private List<User> users;
	private String productName;
	private List<Shelf> shelfs;
	private Shelf shelf;
	private Shelf shelfNow;
	private SimplePager pager;
	private String productId;
	private String[] shelfDelete;
	private Long shelfId;
	private Product product;
	private String jsonShelfDateExist;
	private QuotationService quotationService;
	private QuotationServiceOnline quotationServiceOnline;
	private List<Quotation> quotations;
	private String minDate;
	private Menu shelfStatusMenu;
	private Menu shelfQueryStatusMenu;
	private Menu shelfTypeMenu;
	private String shelfStatus;
	private String approveFailReason;
	private String approve;
	private String loginUser;
	private String shelfType;
	private Map<String, Product> productMap;
	private List<Map<String, Object>> shelfHistoryList;
	/* 上下架商品頁面參數 */
	private String promoteNameParam;
	private String startDateParam;
	private String endDateParam;
	private String timestart;
	private String timeend;
	private String shelfPriceParam;
	private String shelfStatusParam;
	private String shelfMemoParam;

	/*
	 * 审核查询页面参数
	 */
	private String productIdParam;
	private String createUserParam;
	private String statusParam;
	private String createDateParam;

	public String add() throws Exception {
		product = productService.get(productId);
		productName = product.getProductName();
		shelf = null;
		shelfId = null;
		// shelf.setShelfStatus("SHF000");
		approve = null;
		shelfType = "1";
		shelfHistoryList = shelfService.getShelfHistory(productId);
		return "edit";
	}

	/**
	 * 停用上架檔
	 * 
	 * @return
	 * @throws Exception
	 */
	public String delShelf() throws Exception {
		if (null != shelfDelete) { // 停用该上架檔
			for (int i = 0; i < shelfDelete.length; i++) {
				shelf = shelfService.get(Long.parseLong(shelfDelete[i]));
				shelf.setShelfStatus("SHF700");// 下架
				shelfService.update(shelf);
				// shelfService.delete(shelf);
			}
		}
		return list();
	}

	/* 編輯上下架商品 */
	public String edit() throws Exception {
		if (StringUtils.isBlank(productId) || StringUtils.length(productId) != 8 || !NumberUtils.isNumber(productId)) {
			addActionError("传入参数错误");
			return "edit";
		}
		product = productService.get(productId);
		if (null == product) {
			addActionError("查无商品资料(或无该权限查看)");
			return "edit";
		} else {
			productName = product.getProductName();
			if (null != shelfId) {
				try {
					if (StringUtils.isNotBlank(String.valueOf(shelfId))) {
						shelf = shelfService.get(shelfId);
						timestart = FastDateFormat.getInstance("HH:mm").format(shelf.getStartDate());
						timeend = FastDateFormat.getInstance("HH:mm").format(shelf.getEndDate());
					}
					shelfHistoryList = shelfService.getShelfHistory(shelf.getProductId());
				} catch (CoreException e) {
					addActionError(e.getMessage());
					e.printStackTrace();
				}
			}
		}
		return "edit";
	}

	public String view() throws Exception {
		approve = null;
		if (null == shelfId) {
			addActionError("传入参数错误:shelfId=" + shelfId);
			return "list";
		} else {
			shelf = shelfService.get(shelfId);
			if (null == shelf) {
				addActionError("上架檔不存在:shelfId=" + shelfId);
				return "list";
			}
			product = productService.get(shelf.getProductId());
			if (null == product) {
				addActionError("查无商品资料(或无该权限查看)");
				return "list";
			}
			shelfHistoryList = shelfService.getShelfHistory(shelf.getProductId());
		}
		return "view";
	}

	/**
	 * @return the endDateParam
	 */
	public String getEndDateParam() {
		return endDateParam;
	}

	/**
	 * 取得後台成本
	 * 
	 * @return
	 * @throws ParseException
	 * @throws CoreException
	 */
	public String getJsonCheckCost() throws ParseException, CoreException {
		Date start = DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, startDateParam + " "
				+ timestart.trim());
		Date end = DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, endDateParam + " " + timeend.trim());
		start = DateUtil.getFirstTimestamp(Calendar.MINUTE, start);
		end = DateUtil.getLastTimestamp(Calendar.MINUTE, end);
		product = productService.get(productId);
		if (ServletActionContext.getRequest().getServerName().equals("ecadmin.yaodian100.com")) {
			quotations = quotationServiceOnline.getTargetPeriodQuotations(productId, product.getSupplierId(), start, end);
		} else {
			quotations = quotationService.getTargetPeriodQuotations(productId, product.getSupplierId(), start, end);
		}
		return "jsonCheckCost";
	}

	/**
	 * 判断上下架檔期是否重覆
	 * 
	 * @return
	 * @throws ParseException
	 * @throws CoreException
	 */
	public String getJsonCheckIfRecordExist() throws ParseException, CoreException {
		Shelf shelf = new Shelf();
		shelf.setProductId(productId);
		shelf.setStartDate(DateUtils.parseDate(startDateParam + " " + timestart.trim(),
				new String[] { EcConstant.PATTERN_TIMESTAMP_HH_MM }));
		shelf.setEndDate(DateUtils.parseDate(endDateParam + " " + timeend.trim(),
				new String[] { EcConstant.PATTERN_TIMESTAMP_HH_MM }));
		// if (shelfService.checkIfRecordExist(shelf)) {
		// jsonShelfDateExist = "Y";
		// } else {
		// jsonShelfDateExist = "N";
		// }
		jsonShelfDateExist = "N";
		return "jsonCheckIfRecordExist";

	}

	public String getJsonShelfDateExist() {
		return jsonShelfDateExist;
	}

	public String getMinDate() {
		return minDate;
	}

	/**
	 * @return the pager
	 */
	public SimplePager getPager() {
		return pager;
	}

	public Product getProduct() {
		return product;
	}

	/**
	 * @return the productId
	 */
	public String getProductId() {
		return productId;
	}

	/**
	 * @return the productName
	 */
	public String getProductName() {
		return productName;
	}

	/**
	 * @return the promoteNameParam
	 */
	public String getPromoteNameParam() {
		return promoteNameParam;
	}

	public List<Quotation> getQuotations() {
		return quotations;
	}

	/**
	 * @return the shelf
	 */
	public Shelf getShelf() {
		return shelf;
	}

	/**
	 * @return the shelfDelete
	 */
	public String[] getShelfDelete() {
		return shelfDelete;
	}

	/**
	 * @return the shelfId
	 */
	public Long getShelfId() {
		return shelfId;
	}

	/**
	 * @return the shelfMemoParam
	 */
	public String getShelfMemoParam() {
		return shelfMemoParam;
	}

	/**
	 * @return the shelfPriceParam
	 */
	public String getShelfPriceParam() {
		return shelfPriceParam;
	}

	/**
	 * @return the shelfs
	 */
	public List<Shelf> getShelfs() {
		return shelfs;
	}

	/**
	 * @return the shelfService
	 */
	public ShelfService getShelfService() {
		return shelfService;
	}

	/**
	 * @return the shelfStatusParam
	 */
	public String getShelfStatusParam() {
		return shelfStatusParam;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */

	/**
	 * @return the startDateParam
	 */
	public String getStartDateParam() {
		return startDateParam;
	}

	/**
	 * @return the timeend
	 */
	public String getTimeend() {
		return timeend;
	}

	/**
	 * @return the timestart
	 */
	public String getTimestart() {
		return timestart;
	}

	/* 上下架商品列表 */
	public String list() throws Exception {
		approve = null;
		if (StringUtils.isBlank(productId) || StringUtils.length(productId) != 8 || !NumberUtils.isNumber(productId)) {
			addActionError("传入参数错误");
			return "prdTIndex";
		} else {
			product = productService.get(productId);
			if (null == product) {
				addActionError("查无商品资料(或无该权限查看)");
				return "prdTIndex";
			} else {
				loginUser = AdminHelper.getUser().getUsername();
				productName = product.getProductName();
				String[] sortOrder = { "shelfId" };
				crit = new CommonCriteria();
				List<String> statusList = null;
				crit.addEq("productId", productId);
				if (StringUtils.isNotBlank(shelfStatusParam)) {
					if (StringUtils.endsWithIgnoreCase("Y", shelfStatusParam)) {
						statusList = new ArrayList<String>();
						statusList.add("SHF000");
						statusList.add("SHF500");
						crit.addIn("shelfStatus", statusList);
					} else if (StringUtils.endsWithIgnoreCase("N", shelfStatusParam)) {
						statusList = new ArrayList<String>();
						statusList.add("SHF600");
						statusList.add("SHF700");
						crit.addIn("shelfStatus", statusList);
					}
				} else {
					statusList = new ArrayList<String>();
					statusList.add("SHF000");
					statusList.add("SHF500");
					crit.addIn("shelfStatus", statusList);
				}
				int entitySize = shelfService.getListSize(crit).intValue();
				pager.setTotalSize(entitySize);
				pager.setPageRecord(10);// defaut 20
				shelfs = shelfService.getList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(), crit,
						sortOrder);
				shelfNow = shelfService.getActiveShelfByProductId(productId);
				return "list";
			}
		}
	}

	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (pager == null) {
			pager = new SimplePager();
		}
		if (StringUtils.isBlank(minDate)) {
			minDate = DateUtil.convertDateToString("yyyy,MM - 1,dd", DateUtil.getTodayAddDays(-60).getTime());
		}
		if (null == shelfStatusMenu) {
			shelfStatusMenu = menuService.get("Shelf.Status");
		}

		// 找出所有ｐｍ的user
		if (null == users) {
			users = userService.getByRole(Role.Default.PM.name(), Role.Type.OTHER);
		}

		if (null == shelfQueryStatusMenu) {
			shelfQueryStatusMenu = menuService.get("Shelf.QueryStatus");
		}

		if (null == shelfTypeMenu) {
			shelfTypeMenu = menuService.get("Shelf.Type");
		}

		logger.info("prepare ok");
	}

	/**
	 * 儲存上下架商品資料 *
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		if (StringUtils.isBlank(productId) || StringUtils.length(productId) != 8 || !NumberUtils.isNumber(productId)) {
			addActionError("传入参数错误");
		} else {
			approve = null;
			product = productService.get(productId);
			if (null == product) {
				addActionError("查无商品资料(或无该权限查看)");
			} else {
				DateFormat format = new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP);
				if (null != shelfId) {
					shelf = shelfService.get(shelfId);
				} else {
					shelf = new Shelf();
					shelf.setProductId(productId);
				}

				shelf.setPromoteName(promoteNameParam);
				shelf.setShelfPrice(new BigDecimal(shelfPriceParam).setScale(1, BigDecimal.ROUND_FLOOR));
				shelf.setStartDate(format.parse(startDateParam + " " + timestart.trim() + ":00"));
				Calendar cal = Calendar.getInstance();
				cal.setTime(format.parse(endDateParam + " " + timeend.trim() + ":59"));
				// cal.add(Calendar.SECOND, -1);
				shelf.setEndDate(cal.getTime());
				shelf.setShelfMemo(shelfMemoParam);
				if (shelf.getShelfPrice().floatValue() < product.getProductCost().floatValue()) {
					shelf.setShelfStatus("SHF000");
				} else {
					shelf.setShelfStatus("SHF500");
				}
				// if (shelfService.checkIfRecordExist(shelf)) { // 判斷是否重覆上架日期
				// addActionMessage("重覆上下架时间");
				// return edit();
				// }
				if (StringUtils.isNotBlank(shelfType)) {
					shelf.setShelfType(shelfType);
				} else {
					shelf.setShelfType("1");// defult 一般
				}
				shelf.setGiveBonus(0);// 赠送赠物金点数default 0
				shelf.setApproveDate(null);
				shelf.setApproveFailReason(null);
				shelf.setApproveUser(null);
				shelf = shelfService.saveOrUpdateShelf(shelf);
			}
		}
		return list();
	}

	public String saveApprove() throws Exception {
		if (null == shelfId) {
			addActionError("错误的上架檔编号:id=" + shelfId);
			return edit();
		}
		loginUser = AdminHelper.getUser().getUsername();
		shelf = shelfService.get(shelfId);
		shelf.setShelfStatus(shelfStatus);
		shelf.setApproveUser(loginUser);
		shelf.setApproveDate(new Date());
		if (StringUtils.equals("SHF600", shelfStatus)) {
			if (StringUtils.isNotBlank(approveFailReason)) {
				shelf.setApproveFailReason(approveFailReason);
			} else {
				addActionError("请输入审核失败理由");
				return edit();
			}
		}
		shelf = shelfService.saveOrUpdateShelf(shelf);
		shelfId = shelf.getShelfId();
		approve = null;
		return view();
	}

	public String searchApprove() throws Exception {
		loginUser = AdminHelper.getUser().getUsername();
		Map<String, Object> attrs = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(productIdParam)) {
			attrs.put("productId", productIdParam);
		}
		if (StringUtils.isNotBlank(createUserParam)) {
			attrs.put("createUser", createUserParam);
		}
		if (StringUtils.isNotBlank(createDateParam)) {
			attrs.put("createDate", DateUtil.convertStringToDate(createDateParam + " 23:59:59"));
		}
		if (StringUtils.isNotBlank(statusParam)) {
			attrs.put("shelfStatus", statusParam);
		} else {
			statusParam = "SHF000";
			attrs.put("shelfStatus", "SHF000");
		}
		int entitySize = 0;
		entitySize = shelfService.getShelfApproveListSize(attrs).intValue();
		pager.setTotalSize(entitySize);
		shelfs = shelfService.getShelfApproveList(attrs, null, pager.getCurrentPage() * pager.getPageRecord(), pager
				.getPageRecord());
		productMap = new HashMap<String, Product>();
		for (Shelf shelf : shelfs) {
			productMap.put(shelf.getProductId(), productService.get(shelf.getProductId()));
		}
		return "listApprove";
	}

	/**
	 * @param endDateParam the endDateParam to set
	 */
	public void setEndDateParam(String endDateParam) {
		this.endDateParam = endDateParam;
	}

	public void setJsonShelfDateExist(String jsonShelfDateExist) {
		this.jsonShelfDateExist = jsonShelfDateExist;
	}

	public void setMinDate(String minDate) {
		this.minDate = minDate;
	}

	/**
	 * @param pager the pager to set
	 */
	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	/**
	 * @param productId the productId to set
	 */
	public void setProductId(String productId) {
		this.productId = productId;
	}

	/**
	 * @param productName the productName to set
	 */
	public void setProductName(String productName) {
		this.productName = productName;
	}

	/**
	 * @param productService the productService to set
	 */
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	/**
	 * @param promoteNameParam the promoteNameParam to set
	 */
	public void setPromoteNameParam(String promoteNameParam) {
		this.promoteNameParam = promoteNameParam;
	}

	public void setQuotations(List<Quotation> quotations) {
		this.quotations = quotations;
	}

	public void setQuotationService(QuotationService quotationService) {
		this.quotationService = quotationService;
	}

	public void setQuotationServiceOnline(QuotationServiceOnline quotationServiceOnline) {
		this.quotationServiceOnline = quotationServiceOnline;
	}

	/**
	 * @param shelf the shelf to set
	 */
	public void setShelf(Shelf shelf) {
		this.shelf = shelf;
	}

	/**
	 * @param shelfDelete the shelfDelete to set
	 */
	public void setShelfDelete(String[] shelfDelete) {
		this.shelfDelete = shelfDelete;
	}

	/**
	 * @param shelfId the shelfId to set
	 */
	public void setShelfId(Long shelfId) {
		this.shelfId = shelfId;
	}

	/**
	 * @param shelfMemoParam the shelfMemoParam to set
	 */
	public void setShelfMemoParam(String shelfMemoParam) {
		this.shelfMemoParam = shelfMemoParam;
	}

	/**
	 * @param shelfPriceParam the shelfPriceParam to set
	 */
	public void setShelfPriceParam(String shelfPriceParam) {
		this.shelfPriceParam = shelfPriceParam;
	}

	/**
	 * @param shelfs the shelfs to set
	 */
	public void setShelfs(List<Shelf> shelfs) {
		this.shelfs = shelfs;
	}

	/**
	 * @param shelfService the shelfService to set
	 */
	public void setShelfService(ShelfService shelfService) {
		this.shelfService = shelfService;
	}

	/**
	 * @param shelfStatusParam the shelfStatusParam to set
	 */
	public void setShelfStatusParam(String shelfStatusParam) {
		this.shelfStatusParam = shelfStatusParam;
	}

	/**
	 * @param startDateParam the startDateParam to set
	 */
	public void setStartDateParam(String startDateParam) {
		this.startDateParam = startDateParam;
	}

	/**
	 * @param timeend the timeend to set
	 */
	public void setTimeend(String timeend) {
		this.timeend = timeend;
	}

	/**
	 * @param timestart the timestart to set
	 */
	public void setTimestart(String timestart) {
		this.timestart = timestart;
	}

	public DomainService<Menu> getMenuService() {
		return menuService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public Menu getShelfStatusMenu() {
		return shelfStatusMenu;
	}

	public void setShelfStatusMenu(Menu shelfStatusMenu) {
		this.shelfStatusMenu = shelfStatusMenu;
	}

	public String getShelfStatus() {
		return shelfStatus;
	}

	public void setShelfStatus(String shelfStatus) {
		this.shelfStatus = shelfStatus;
	}

	public String getApproveFailReason() {
		return approveFailReason;
	}

	public void setApproveFailReason(String approveFailReason) {
		this.approveFailReason = approveFailReason;
	}

	public String getApprove() {
		return approve;
	}

	public void setApprove(String approve) {
		this.approve = approve;
	}

	public String getLoginUser() {
		return loginUser;
	}

	public void setLoginUser(String loginUser) {
		this.loginUser = loginUser;
	}

	public List<Map<String, Object>> getShelfHistoryList() {
		return shelfHistoryList;
	}

	public void setShelfHistoryList(List<Map<String, Object>> shelfHistoryList) {
		this.shelfHistoryList = shelfHistoryList;
	}

	public Map<String, Product> getProductMap() {
		return productMap;
	}

	public void setProductMap(Map<String, Product> productMap) {
		this.productMap = productMap;
	}

	public String getProductIdParam() {
		return productIdParam;
	}

	public void setProductIdParam(String productIdParam) {
		this.productIdParam = productIdParam;
	}

	public String getCreateUserParam() {
		return createUserParam;
	}

	public void setCreateUserParam(String createUserParam) {
		this.createUserParam = createUserParam;
	}

	public String getStatusParam() {
		return statusParam;
	}

	public void setStatusParam(String statusParam) {
		this.statusParam = statusParam;
	}

	public String getCreateDateParam() {
		return createDateParam;
	}

	public void setCreateDateParam(String createDateParam) {
		this.createDateParam = createDateParam;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public Menu getShelfQueryStatusMenu() {
		return shelfQueryStatusMenu;
	}

	public void setShelfQueryStatusMenu(Menu shelfQueryStatusMenu) {
		this.shelfQueryStatusMenu = shelfQueryStatusMenu;
	}

	public Menu getShelfTypeMenu() {
		return shelfTypeMenu;
	}

	public void setShelfTypeMenu(Menu shelfTypeMenu) {
		this.shelfTypeMenu = shelfTypeMenu;
	}

	public String getShelfType() {
		return shelfType;
	}

	public void setShelfType(String shelfType) {
		this.shelfType = shelfType;
	}

	public Shelf getShelfNow() {
		return shelfNow;
	}

	public void setShelfNow(Shelf shelfNow) {
		this.shelfNow = shelfNow;
	}
}